<template>
    <el-form label-width="120px">
        <el-form-item label="SPU名称">
            <el-input v-model="SpuParams.spuName" placeholder="请输入SPU名称"></el-input>
        </el-form-item>
        <el-form-item label="SPU品牌">
            <el-select v-model="SpuParams.tmId">
                <el-option v-for="item in AllTrademark" :label="item.tmName" :value="item.id" />
            </el-select>
        </el-form-item>
        <el-form-item label="SPU描述">
            <el-input type="textarea" v-model="SpuParams.description" />
        </el-form-item>
        <el-form-item label="SPU图片">
            <!-- 
                v-model:fileList->展示默认图片
                action:上传图片的接口地址
                list-type:文件的类型
             -->
            <el-upload v-model:file-list="imageList" action="/api/admin/product/fileUpload" list-type="picture-card"
                :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :before-upload="handlerUpload">
                <el-icon>
                    <Plus />
                </el-icon>
            </el-upload>

            <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
        </el-form-item>

        <el-form-item label="SPU销售属性">
            <!-- 展示销售属性的下拉菜单 -->
            <el-select :placeholder="unSelectSaleArr.length ? `还有${unSelectSaleArr.length}个未选择` : '无'"
                v-model="saleAttrIdAndValueName">
                <el-option v-for="item in unSelectSaleArr" :key="item.id"
                    :label="item.name" :value="`${item.id}:${item.name}`" />
            </el-select>
            <el-button type="primary" icon="Plus" class="ml-3" @click="addSaleAttr"
                :disabled="saleAttrIdAndValueName ? false : true">添加属性</el-button>
            <!-- table 展示销售属性与属性值的地方 -->
            <el-table border class="my-3" :data="SaleAttr">
                <el-table-column label="序号" type="index" width="80" align="center" />
                <el-table-column label="销售属性名字" property="saleAttrName" width="180" align="center" />

                <el-table-column label="销售属性值">
                    <template #="{ row }">
                        <el-tag v-for="(item, index) in row.spuSaleAttrValueList" :key="item.id" class="mx-3" closable
                            @close="row.spuSaleAttrValueList.splice(index, 1)">
                            {{ item.saleAttrValueName }}
                        </el-tag>
                        <el-input v-if="row.flag == true" class="w-40 m-2" size="small" placeholder="请输入属性值"
                            v-model="row.saleAttrValue" @blur="toLook(row)"></el-input>
                        <el-button v-else type="primary" size="small" icon="Plus" @click="toEdit(row)"></el-button>
                    </template>
                </el-table-column>>
                <!-- 删除 -->
                <el-table-column label="操作" width="150" align="center">
                    <template #="{ $index }">
                        <el-button icon="Delete" type="warning" size="small" @click="SaleAttr.splice($index, 1)" />
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>
        <!-- 操作的保存和取消 -->
        <el-form-item>
            <el-button type="primary" @click="save">保存</el-button>
            <el-button type="primary" @click="cancel">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus'
let $emit = defineEmits(['changeScene'])
//引入接口
import { reqAllTrademarkSpu, reqSpuImageList, reqSpuHasSaleAttr, reqAllSaleAttr, reqAddOrUpdateSpu, } from '../../../api/product/spu/index';
//子组件点击取消按钮:通知父组件切换场景为1,展示已有的spu数据
const cancel = () => {
    $emit('changeScene', {flag:0,params:'updata'})
}
// const a=ref()

const dialogImageUrl = ref<any>('')
const dialogVisible = ref<boolean>(false)

//存储已有的spu品牌数据
let AllTrademark = ref<any>([])
//商品图片
let imageList = ref<any>([])
//已有的spu销售属性
let SaleAttr = ref<any>([])
//全部的销售属性
let AllSaleAttr = ref<any>([])
//存储已有的spu对象
let SpuParams = ref<any>({
    category3Id: '',//收集三级分类的id
    spuName: '',//spu的名字
    description: "",//spu的描述
    tmId: '',//品牌的id
    spuImageList: [],
    spuPosterList: [],
    spuSaleAttrList: [],
})
//将来收集还未选择的销售的id与属性值的方法
let saleAttrIdAndValueName = ref<string>('')
// 子组件中书写一个方法
const initHasSpuData = async (spu: any) => {
    //存储已有的spu对象,将来在模板中展示
    SpuParams.value = spu
    // SPU即为父组件传递过来的已有spu对象(不完整)
    //获取全部品牌的数据
    const result: any = await reqAllTrademarkSpu()
    //获取某一个品牌旗下全部售卖商品的图片
    const result1: any = await reqSpuImageList(spu.id)
    //获取已有的SPU销售属性的数据
    const result2: any = await reqSpuHasSaleAttr(spu.id)
    //获取整个项目全部的spu 的销售属性
    const result3: any = await reqAllSaleAttr()

    //存储全部品牌的数据
    AllTrademark.value = result.data
    //spu对应商品图片
    imageList.value = result1.data.map(item => {
        return {
            name: item.imgName,
            url: item.imgUrl
        }
    })
    //存储已有的spu 销售属性
    SaleAttr.value = result2.data
    //存储全部的销售属性
    AllSaleAttr.value = result3.data
}


//照片删除的钩子
const handleRemove = () => {
    console.log('上传成功!')
}
//照片墙点击预览时的钩子
const handlePictureCardPreview = (File: any) => {
    dialogImageUrl.value = File.url
    //对话框弹出来
    dialogVisible.value = true
}
//文件上传类型的限制
const handlerUpload = (File: any) => {
    if (File.type == "image/png" || File.type == "image/jpeg") {
        return true
    } else {
        ElMessage({
            showClose: true,
            message: '文件类型错误',
            type: 'info',
        })
        return false
    }
}

//计算出当前spu还未拥有的销售属性
let unSelectSaleArr = computed(() => {
    //全部销售属性:颜色 版本 尺码
    //已有的销售属性:颜色 版本
    let unSelectArr = AllSaleAttr.value.filter(item => {
        return SaleAttr.value.every(item1 => {
            return item.name != item1.saleAttrName
        })
    })
    return unSelectArr
})

//属性值的按钮的点击事件
const toEdit = (row: any) => {
    row.flag = true
    row.saleAttrValue = ''
}

const addSaleAttr = () => {
    /*
    "baseSaleAttrId": number,
    "saleAttrName": string,
    "spuSaleAttrValueList": SpuSaleAttrValueList
    */
    const [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':');
    //准备一个新的销售属性对象:将来带给服务器即可
    let newSaleAttr: any = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: []
    }
    //追加到数组当中
    SaleAttr.value.push(newSaleAttr);
    //清空收集的数据
    saleAttrIdAndValueName.value = '';

}

//表单元素失去焦点的事件的回调
const toLook = (row: any) => {
    //整理收集属性的id与属性值的名字
    const { baseSaleAttrId, saleAttrValue } = row
    //整理成服务器需要的属性值的形式
    let newSaleAttrValue = {
        baseSaleAttrId,
        saleAttrValueName: saleAttrValue
    }
    // 判断是否非法情况
    if (saleAttrValue.trim() == '') {
        ElMessage({
            showClose: true,
            message: '属性值不得为空',
            type: 'info',
        })
        return row.flag = false
    }
    //属性名字是否重复 重复返回true 否则false
    let repeat = row.spuSaleAttrValueList.find(item => {
        return item.saleAttrValueName == saleAttrValue
    })
    //判断是否重复 是否进行下一步操作   
    if (repeat) {
        ElMessage({
            showClose: true,
            message: '属性值不得重复',
            type: 'error',
        })
        return row.flag = false
    }
    //追加新的属性值
    row.spuSaleAttrValueList.push(newSaleAttrValue)
    //切看查看模式
    row.flag = false
}

//保存按钮的回调
const save = async () => {
    //整理参数
    //1:照片墙的数据
    // let  imageList
    SpuParams.value.spuImageList = imageList.value.map(item => {
        return {
            imgName: item.name,//图片的名字
            imgUrl: (item.response && item.response.data) || item.url//图片的地址
        }
    })
    //2:整理销售属性的数据
    SpuParams.value.spuSaleAttrList = SaleAttr.value
    // // 3:
    // SpuParams.value.spuSaleAttrList=AllSaleAttr.value
    // 发送请求:添加|修改spu数据
    const result: any = await reqAddOrUpdateSpu(SpuParams.value)
    console.log(result);
    
    //  成功:
    if (result.code == 200) {
        ElMessage({
            showClose: true,
            message: SpuParams.value.id ? "修改成功" : '添加成功',
            type: 'success',
        })
        //通知父组件切换场景为0
        $emit('changeScene', {flag:0,params: SpuParams.value.id?'undata':'add'})

    } else {
        ElMessage({
            showClose: true,
            message: SpuParams.value.id ? "修改失败" : '添加失败',
            type: 'info',
        })
    }
}


//添加一个新的SPU初始化请求的方法
const initAddSpu = async (c3Id: number | string) => {
    //清空数据
    Object.assign(SpuParams.value, {
        category3Id: '',//收集三级分类的id
        spuName: '',//spu的名字
        description: "",//spu的描述
        tmId: '',//品牌的id
        spuImageList: [],
        spuSaleAttrList: [],
    })
    imageList.value=[],
    SaleAttr.value=[],
    saleAttrIdAndValueName.value=''
    SpuParams.value.category3Id = c3Id
    const result: any = await reqAllTrademarkSpu()
    const result3: any = await reqAllSaleAttr()
    //存储全部品牌的数据
    AllTrademark.value = result.data
    //存储全部的销售属性
    AllSaleAttr.value = result3.data
}

//对外暴露
defineExpose({ initHasSpuData, initAddSpu })
</script>

<style lang="scss" scoped></style>

